<template>
  <div v-if="!modifyDeliverInfo.visible" class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="订单明细"
      @returnBack="returnBack"
    >
      <template v-slot:full-button>
        <el-button v-if="infoList.data.status === 1" @click="shipment"
          >发货</el-button
        >
        <el-button v-if="infoList.data.status === 2 && !type" @click="invalid"
          >作废</el-button
        >
        <el-button
          v-if="
            (infoList.data.status === 2 || infoList.data.status === 3) &&
            type === 'pendDealDeliverOrder' &&
            $permission('pendDealDeliverOrder:receiving')
          "
          @click="receiving"
          >收货</el-button
        >
        <el-button @click="printCode" v-if="infoList.data.status !== 1"
          >打印二维码</el-button
        >
        <el-button @click="print" v-if="infoList.data.status !== 1"
          >打印</el-button
        >
        <!-- <el-button @click="excel">导出excel</el-button> -->
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <BasicInformation
            :info="infoList"
            :labelWidth="infoList.labelWidth"
          >
          <template v-slot:basic-isWayBill>
            {{ infoList.data.isWayBill ? '是' : '否' }}
          </template>
          <template v-slot:basic-filePathList>
                <EleGallery
                  v-if="infoList.data.filePathList"
                  :lazy="true"
                  :size="150"
                  :source="infoList.data.filePathList"
                  title="附件"
                />
                <span v-else>-</span>
              </template>
        </BasicInformation>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <div class="flex_full_item">
            <!-- 表格 -->
            <PageTable
              :refresh="tableInfo.refresh"
              :init-curpage="tableInfo.initCurpage"
              v-model:data="tableInfo.data"
              :pager="false"
              :summary="true"
              :api="mergeDeliverOrderDetail"
              :summaryFieldList="tableInfo.summaryFieldList"
              :checkBox="false"
              :tab-index="true"
              v-model:query="filterInfo.query"
              :field-list="tableInfo.fieldList"
              :handle="tableInfo.handle"
              :mergeData="tableInfo.mergeData"
              :mergeFiled="tableInfo.mergeFiled"
              :isDynamic="true"
              @handleEvent="handleEvent"
            >
              <template v-slot:col-licenseNumber="scope">
                <p>{{ scope.row.licenseNumber || '-' }}</p>
                <p>{{ scope.row.brandName || '-' }}</p>
              </template>
              <template v-slot:col-commonName="scope">
                <p>{{ scope.row.commonName || '-' }}</p>
                <p>{{ scope.row.productCode || '-' }}</p>
                <p>{{ scope.row.alias || '-' }}</p>
              </template>
              <template v-slot:col-type="scope">
                <p>{{ scope.row.productTypeValue || '-' }}</p>
                <p>{{ scope.row.codeTypeValue || '-' }}</p>
                <p>{{ scope.row.productCategoryValue || '-' }}</p>
              </template>
              <template v-slot:col-standard="scope">
                <p>{{ scope.row.standard || '-' }}</p>
                <p>{{ scope.row.unitName || '-' }}</p>
              </template>
              <template v-slot:col-calcUnitName="scope">
                <p>{{ scope.row.calcUnitName || '-' }}</p>
                <p>{{ scope.row.unitConvertCoefficient || '-' }}</p>
              </template>
            </PageTable>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <ChosePrinter :visible="printerInfo.visible" @callBack="printerCallBack" />
  </div>
  <IndividualDetails
    v-if="individualDetailInfo.visible"
    v-model:show-dialog="individualDetailInfo.visible"
    v-model:query="individualDetailInfo.query"
    :info="individualDetailInfo.data"
    :status="infoList.data.status"
    :infoListData="infoList.data"
    :tableData="tableInfo.data"
    :tableIndex="individualDetailInfo.index"
    :type="type"
    @reset="returnDetail"
  />
  <ReceivingModifyOrder
    v-if="modifyDeliverInfo.visible"
    v-model:visible="modifyDeliverInfo.visible"
    :title="modifyDeliverInfo.title"
    :deliver-id="modifyDeliverInfo.deliverId"
    :order-id="modifyDeliverInfo.orderId"
    :receive-all="modifyDeliverInfo.receiveAll"
    @returnModify="returnReceiving"
  ></ReceivingModifyOrder>
  <page-dialog
    v-if="dialogInfo.visible"
    :title="dialogInfo.title"
    v-model:visible="dialogInfo.visible"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <page-form
      class="paddingBox order-model-formBox flex_wrap_start_start"
      v-model:ref-obj="formInfo.ref"
      :data="formInfo.data"
      :field-list="
        formInfo.data.codeType == 3
          ? formInfo.fieldListFactory
          : formInfo.fieldList
      "
      :rules="
        formInfo.data.codeType == 3
          ? formInfo.rulesFactory
          : formInfo.data.needBatchNumber == 1
          ? formInfo.rulesbatch
          : formInfo.rules
      "
      :label-width="formInfo.labelWidth"
    >
      <template v-slot:form-largeUnitQty>
        <div class="page-table-input-number-wrapper">
          <div class="page-table-input-number-left">
            <div class="page-table-input-number-item">
              <el-input-number
                v-model.lazy="formInfo.data.largeUnitQty"
                style="width: 100%"
                clearable
                controls-position="right"
                :precision="
                  formInfo.data.qtyOperateMode === 0 ||
                  formInfo.data.qtyOperateMode === 2
                    ? 0
                    : systemConfig.qty_show_precision
                "
                :min="0"
                :max="largeMaxRow(formInfo.data)"
                @change="changeQty"
              />
              <div class="page-table-input-number-item-unite">
                {{ formInfo.data.unitName }}
              </div>
            </div>
            <div
              class="page-table-input-number-item"
              v-if="
                formInfo.data.unitConvertCoefficient > 1 &&
                formInfo.data.qtyOperateMode === 2
              "
            >
              <el-input-number
                style="width: 100%"
                v-model.lazy="formInfo.data.smallUnitQty"
                clearable
                controls-position="right"
                :precision="0"
                :min="0"
                :max="formInfo.data.unitConvertCoefficient - 1"
                @change="changeQty"
              />
              <div class="page-table-input-number-item-unite">
                {{ formInfo.data.calcUnitName }}
              </div>
            </div>
          </div>
          <div
            class="page-table-input-number-right"
            v-if="formInfo.data.qtyOperateMode === 2"
          >
            {{ $fn.qtyFormatter(formInfo.data.qty) }}
          </div>
        </div>
      </template>
      <template v-slot:form-qty>
        <span>{{ $fn.qtyFormatter(formInfo.data.qty) }}</span>
      </template>
      <template v-slot:form-price>
        <el-input-number
          v-model="formInfo.data.price"
          :precision="systemConfig.price_precision"
          :max="999999999999999"
          clearable
          controls-position="right"
          :min="0"
          @change="changePrice"
        ></el-input-number>
        <p
          style="color: red"
          v-if="
            formInfo.data.isLimitPrice == 1 &&
            formInfo.data.price > formInfo.data.purchaseLimitPrice
          "
        >
          超过产品限价:{{ formInfo.data.purchaseLimitPrice }}
        </p>
      </template>
      <template v-slot:form-sterilizationNumber>
        <el-input
          v-model="formInfo.data.sterilizationNumber"
          placeholder="请输入灭菌批号"
          :minlength="0"
          :maxlength="50"
          @change="changeSterilization"
        ></el-input>
      </template>
    </page-form>
    <ScanInputBox
      v-if="formInfo.data.codeType == 3"
      :query="scanInfo.query"
      :table-data="[formInfo.data]"
      :api="scanInfo.api"
      :get-product-ids="scanInfo.getProductIds"
      @callback="onCallBackScanData"
    />
    <el-form
      v-if="formInfo.data.codeType == 3"
      ref="tableForm"
      :model="formInfo.data"
      style="width: 100%"
    >
      <DialogTable
        v-model:data="formInfo.data.details"
        :field-list="dialogTable.fieldList"
        :handle="dialogTable.handle"
        :check-box="false"
        :tabIndex="true"
        :pager="false"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-qty="scope">
          <el-form-item class="margin-bottom">
            <div class="page-table-input-number-wrapper">
              <div class="page-table-input-number-left">
                <div class="page-table-input-number-item">
                  <el-form-item>
                    <el-input-number
                      v-model.lazy="scope.row.largeUnitQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="
                        scope.row.qtyOperateMode === 0 ||
                        scope.row.qtyOperateMode === 2
                          ? 0
                          : systemConfig.qty_show_precision
                      "
                      :min="0"
                      :max="largeMax(scope.row)"
                      @change="changeLarge($event, scope.row)"
                    />
                  </el-form-item>
                  <div class="page-table-input-number-item-unite">
                    {{ scope.row.unitName }}
                  </div>
                </div>
                <div
                  v-if="
                    scope.row.unitConvertCoefficient > 1 &&
                    scope.row.qtyOperateMode === 2
                  "
                  class="page-table-input-number-item"
                >
                  <el-form-item>
                    <el-input-number
                      v-model.lazy="scope.row.smallUnitQty"
                      style="width: 100%; margintop: 18px"
                      clearable
                      controls-position="right"
                      :precision="0"
                      :min="0"
                      :max="smallMax(scope.row)"
                      @change="changeSmall($event, scope.row)"
                    />
                  </el-form-item>
                  <div class="page-table-input-number-item-unite">
                    {{ scope.row.calcUnitName }}
                  </div>
                </div>
              </div>
              <div
                v-if="scope.row.qtyOperateMode === 2"
                class="page-table-input-number-right"
              >
                {{ $fn.qtyFormatter(scope.row.qty) }}
              </div>
            </div>
          </el-form-item>
        </template>
      </DialogTable>
    </el-form>
  </page-dialog>
</template>

<script setup name="deliverOrderDetail">
import IndividualDetails from './IndividualDetails'
import EleGallery from '@/components/UploadImgNew/eleGallery'
import {
  getDeliverOrderById,
  mergeDeliverOrderDetail,
  shipmentsGoods,
  printQrCode,
  deliverOrderDetailInvalid,
  deliverOrderValidateLicense,
  deliverOrderScan,
  deliverOrderReshipment,
} from '@/api/supplier.js'
import ScanInputBox from './ScanInputBox'
const ReceivingModifyOrder = defineAsyncComponent(() =>
  import('@/views/stock/receiving/importModifyOrder')
)
const emit = defineEmits()
const { proxy } = getCurrentInstance()
const store = useStore()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  id: {
    type: [Boolean, String],
  },
  type: {
    type: [Boolean, String],
  },
})
const systemConfig = ref(store.state.permission.systemConfig)
const infoList = ref({
  data: {},
  fieldList: [
    { label: '发货单号', value: 'orderNo', type: 'text' },
    { label: '销售单号', value: 'saleNo', type: 'text' },
    { label: '采购单号', value: 'purchNo', type: 'text' },
    { label: '发票号码', value: 'invoiceNumber', type: 'text' },
    { label: '货单号码', value: 'waybillNumber', type: 'text' },
    { label: '客户', value: 'hospitalName', type: 'text' },
    { label: '客户部门', value: 'deptName', type: 'text' },
    { label: '预计发货日期', value: 'expectedDeliverTime', type: 'text' },
    { label: '收货地址', value: 'receiveAddressValue', type: 'text' },
    { label: '收货联系人', value: 'receiveContacts', type: 'text' },
    { label: '联系人电话', value: 'receivePhone', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '是否暂估入库',
      value: 'isEstimationStockBusinessValue',
      type: 'text',
      show:
        proxy.$store.state.permission.systemConfig
          .is_estimation_stock_business == 1,
    },
    {
      label: '配送方式',
      value: 'deliveryTypeValue',
      type: 'text',
    },
     {
      label: '配送人',
      value: 'deliveryUser',
      type: 'text',
    },
     {
      label: '配送人电话',
      value: 'deliveryPhone',
      type: 'text',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'popover',
    },
    {
      label: '是否货票同行',
      value: 'isWayBill',
      type: 'slot',
    },
    {
      label: '附件',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  labelWidth: '130px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    orderId: props.id,
  },
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'receiveQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'refuseQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  selections: [],
  data: [],
  mergeData: {},
  mergeFiled: [
    'licenseNumber',
    'commonName',
    'type',
    'standard',
    'calcUnitName',
  ],
  fieldList: [
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: 220,
    },
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: 220,
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: 150,
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '计算单位\n转换系数', value: 'calcUnitName', type: 'slot' },
    { label: '生产批号', value: 'batchNumber' },
    { label: '生产日期', value: 'productionDate' },
    { label: '失效日期', value: 'validityDate' },
    {
      label: '结算单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '发货数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '收货数量',
      value: 'receiveQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '拒收数量',
      value: 'refuseQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    { label: '灭菌批号', value: 'sterilizationNumber' },
    { label: '拒收原因', value: 'rejectionReason' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '重新发货',
        event: afreshInvoce,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '撤销发货',
        event: revokeInvoce,
        show: true,
        ifRender: ifRenderRevokeValue,
      },
      {
        label: '个体详情',
        event: singleProductDetails,
        show: true,
      },
    ],
  },
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const individualDetailInfo = ref({
  visible: false,
  query: {},
  index: '',
  data: {},
})
const modifyDeliverInfo = ref({
  visible: false,
  title: '',
  orderId: '',
  deliverId: '',
  receiveAll: true,
})
const scanInfo = ref({
  query: {
    saleId: '',
    hospitalId: '',
  },
  api: deliverOrderScan,
  getProductIds: [],
})
const formInfo = ref({
  ref: null,
  data: {},
  index: '',
  fieldList: [
    {
      label: '发货数量',
      value: 'largeUnitQty',
      type: 'slot',
    },
    {
      label: '批号',
      value: 'batchNumber',
      type: 'input',
    },
    {
      label: '生产日期',
      value: 'productionDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        },
      },
    },
    {
      label: '失效日期',
      value: 'validityDate',
      type: 'date',
      TimePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        },
      },
    },
    {
      label: '结算单价',
      value: 'price',
      type: 'slot',
    },
    {
      label: '灭菌批号',
      value: 'sterilizationNumber',
      type: 'slot',
    },
  ],
  fieldListFactory: [
    {
      label: '发货数量',
      value: 'qty',
      type: 'slot',
    },
    {
      label: '结算单价',
      value: 'price',
      type: 'slot',
    },
    {
      label: '灭菌批号',
      value: 'sterilizationNumber',
      type: 'input',
    },
  ],
  rules: {
    price: [{ required: true, message: '请输入结算单价', trigger: 'blur' }],
    largeUnitQty: [
      {
        required: true,
        validator: proxy.$validate.positive,
        trigger: 'blur',
      },
    ],
  },
  rulesbatch: {
    price: [{ required: true, message: '请输入结算单价', trigger: 'blur' }],
    largeUnitQty: [
      {
        required: true,
        validator: proxy.$validate.positive,
        trigger: 'blur',
      },
    ],
    batchNumber: [
      { required: true, message: '请输入产品批号', trigger: 'blur' },
    ],
    productionDate: [
      { required: true, message: '请输入生产日期', trigger: 'change' },
    ],
    validityDate: [
      { required: true, message: '请输入失效日期', trigger: 'change' },
    ],
  },
  rulesFactory: {
    price: [{ required: true, message: '请输入结算单价', trigger: 'blur' }],
  },
  labelWidth: '120px',
})
const dialogTable = ref({
  data: [],
  fieldList: [
    {
      label: '发货数量',
      value: 'qty',
      type: 'slot',
    },
    { label: '原厂主码', value: 'factoryMainCode' },
    { label: '原厂从码', value: 'factorySubCode' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: remove,
        show: true,
      },
    ],
  },
})
const dialogInfo = ref({
  visible: false,
  title: '重新发货',
  btLoading: false,
  type: '',
  msg: '',
  width: '700px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      tableInfo.value.mergeData = proxy.$fn.getMergeData(val)
    }
  },
  { deep: true }
)
watch(
  () => formInfo.value.data,
  (val) => {
    if (formInfo.value.data.details && formInfo.value.data.details.length) {
      let calcQty = 0
      let largeUnitQty = 0
      let smallUnitQty = 0
      formInfo.value.data.details.forEach((row) => {
        let smallUnitQty1 = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty1 = parseFloat(row.largeUnitQty || 0)
        let calcQty1 = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty1, unitConvertCoefficient),
          smallUnitQty1
        )

        let qty = proxy.$fn.accDiv(calcQty1, unitConvertCoefficient)
        let sumAmount = proxy.$fn.accMul(row.qty, row.price || 0)
        row.calcQty = calcQty1
        row.qty = qty
        row.sumAmount = sumAmount

        calcQty = proxy.$fn.accAdd(row.calcQty, calcQty)
        largeUnitQty = proxy.$fn.accAdd(row.largeUnitQty, largeUnitQty)
        smallUnitQty = proxy.$fn.accAdd(row.smallUnitQty, smallUnitQty)
      })
      formInfo.value.data.calcQty = calcQty
      formInfo.value.data.largeUnitQty = largeUnitQty
      formInfo.value.data.smallUnitQty = smallUnitQty
      formInfo.value.data.qty = proxy.$fn.accDiv(
        calcQty,
        formInfo.value.data.unitConvertCoefficient
      )
    }
  },
  {
    deep: true,
  }
)
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    if (row.codeType === 3) {
      return 1
    }
    return parseInt(row.deliverableCalcQty / row.unitConvertCoefficient)
  } else {
    if (row.codeType === 3) {
      return 1
    }
    return row.deliverableQty
  }
}
function changeSmall(e, row) {
  let item = formInfo.value.data.details.find(
    (item) => item.tableIndex === row.tableIndex
  )
  item.smallUnitQty = e
  if (row.codeType === 3 && row.qtyOperateMode === 2) {
    if (e > 0) {
      row.largeUnitQty = 0
      item.largeUnitQty = 0
    }
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.deliverableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.deliverableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row) {
  let item = formInfo.value.data.details.find(
    (item) => item.tableIndex === row.tableIndex
  )
  item.largeUnitQty = e
  if (row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
      item.smallUnitQty = 0
    }
  } else {
    let largeUnitQty = parseInt(
      row.deliverableCalcQty / row.unitConvertCoefficient
    )
    if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
      if (largeUnitQty > 0 && e === largeUnitQty) {
        let smallUnitQty = parseInt(
          row.deliverableCalcQty % row.unitConvertCoefficient
        )
        if (row.smallUnitQty > smallUnitQty) {
          row.smallUnitQty = smallUnitQty
          item.smallUnitQty = smallUnitQty
        }
      }
    }
  }
}
function changeQty() {
  let row = formInfo.value.data
  let smallUnitQty = parseFloat(row.smallUnitQty || 0)
  let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
  let largeUnitQty = parseFloat(row.largeUnitQty || 0)
  let calcQty = proxy.$fn.accAdd(
    proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
    smallUnitQty
  )
  let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
  formInfo.value.data.calcQty = calcQty
  formInfo.value.data.qty = qty
  formInfo.value.data.sumAmount = proxy.$fn.accDiv(
    proxy.$fn.accMul(row.calcQty, row.price || 0),
    unitConvertCoefficient
  )
}
function largeMaxRow(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.deliverableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.deliverableQty
  }
}
function ifRenderValue() {
  return (
    infoList.value.data.status === 2 && props.type !== 'pendDealDeliverOrder'
  )
}
function ifRenderRevokeValue() {
  return (
    infoList.value.data.status === 2 &&
    props.type !== 'pendDealDeliverOrder' &&
    tableInfo.value.data.length > 1
  )
}

function returnBack() {
  proxy.$emit('returnBack', false)
}
function returnDetail() {
  getList()
  getMain()
}
function receiving() {
  //收货
  modifyDeliverInfo.value.deliverId = infoList.value.data.id
  modifyDeliverInfo.value.orderId = ''
  modifyDeliverInfo.value.visible = true
  modifyDeliverInfo.value.title = '根据发货单导入'
  modifyDeliverInfo.value.receiveAll = true
}
function getList() {
  tableInfo.value.refresh = Math.random()
}
function getMain() {
  getDeliverOrderById(props.id).then((res) => {
    if (res && res.success) {
      infoList.value.data = res.data
      scanInfo.value.query.saleId = res.data.saleId
      scanInfo.value.query.deliverId = res.data.id
      scanInfo.value.query.hospitalId = res.data.hospitalId
    }
  })
}
function print() {
  let printRows = []
  let info = infoList.value.data
  let titles = []
  let fieldList = tableInfo.value.fieldList
  let attrLable = []
  fieldList.forEach((it) => {
    let dataTemp = {
      title: it.label,
      align: 'center',
    }
    titles.push(dataTemp)
    attrLable.push(it.value)
  })
  titles[9].width = 7
  titles[10].width = 7
  for (let p in tableInfo.value.data) {
    let attrs = []
    attrLable.forEach((it) => {
      if (it == 'licenseNumber') {
        let licenseNumber = tableInfo.value.data[p][it] || ''
        licenseNumber += '<br/>' + (tableInfo.value.data[p].brandName || '')
        attrs.push(licenseNumber)
      } else if (it == 'commonName') {
        let commonName = tableInfo.value.data[p][it] || ''
        commonName += '<br/>' + (tableInfo.value.data[p].productCode || '')
        commonName += '<br/>' + (tableInfo.value.data[p].alias || '')
        attrs.push(commonName)
      } else if (it == 'type') {
        let type = tableInfo.value.data[p].productTypeValue || ''
        type += '<br/>' + (tableInfo.value.data[p].codeTypeValue || '')
        type += '<br/>' + (tableInfo.value.data[p].classifyValue || '')
        attrs.push(type)
      } else if (it == 'standard') {
        let standard = tableInfo.value.data[p][it] || ''
        standard += '<br/>' + (tableInfo.value.data[p].unitName || '')
        attrs.push(standard)
      } else if (it == 'calcUnitName') {
        let calcUnitName = tableInfo.value.data[p][it] || ''
        calcUnitName +=
          '<br/>' + (tableInfo.value.data[p].unitConvertCoefficient || '')
        attrs.push(calcUnitName)
      } else {
        attrs.push(tableInfo.value.data[p][it] || '')
      }
    })
    printRows.push(attrs)
  }
  proxy.$print.printOrder(
    {
      title: '发货单',
      qrCode:
        (info.purchNo || '') +
        '-' +
        (info.orderNo || '') +
        '-' +
        (info.invoiceNumber || '') +
        '-' +
        (info.waybillNumber || ''),
      sign: ['科室主任', '经手人'],
      orgName: info.createUserName,
      main: {
        发货单号: info.orderNo || '',
        销售单号: info.saleNo || '',
        采购单号: info.purchNo || '',
        发票号码: info.invoiceNumber || '',
        货单号码: info.waybillNumber || '',
        状态: info.statusValue || '',
        客户: info.hospitalName || '',
        预计发货日期: info.expectedDeliverTime || '',
        收货地址: info.receiveAddress || '',
        收货联系人: info.receiveContacts || '',
        联系人电话: info.receivePhone || '',
        创建人: info.createUserName || '',
        创建时间: info.createTime || '',
        备注: info.remark || '',
      },
      sum: [9, 10],
      titles: titles || [],
      rows: printRows,
    },
    'Horizontal'
  )
}
function excel() {}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function shipment() {
  let ids = [props.id]
  deliverOrderValidateLicense(ids).then((resp) => {
    if (resp && resp.success) {
      shipmentsGoods(ids).then((res) => {
        if (res && res.success) {
          proxy.$emit('returnDetail')
          showDialog.value = false
        }
      })
    }
  })
}
function invalid() {
  deliverOrderDetailInvalid([props.id]).then((res) => {
    if (res && res.success) {
      proxy.$emit('returnDetail')
      showDialog.value = false
    }
  })
}
function printCode() {
  printQrCode([props.id]).then((resp) => {
    if (resp && resp.success) {
      printerInfo.value.visible = true
      printerInfo.value.data = resp.data
    }
  })
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function singleProductDetails(row, index) {
  const params = {
    sort: 'unique_code ASC',
    orderId: props.id,
    productId: row.productId,
    batchNumber: row.batchNumber,
    validityDate: row.validityDate,
    productionDate: row.productionDate,
    price: row.price,
    sterilizationNumber: row.sterilizationNumber,
  }
  if (!row.batchNumber) {
    params.batchNumberisEmpty = 'isEmpty'
  }
  if (!row.validityDate) {
    params.validityDateisEmpty = 'isEmpty'
  }
  if (!row.productionDate) {
    params.productionDateisEmpty = 'isEmpty'
  }
  individualDetailInfo.value.data = row
  individualDetailInfo.value.index = index
  individualDetailInfo.value.query = params
  individualDetailInfo.value.visible = true
}
function changePrice(val) {
  if (
    formInfo.value.data.codeType === 3 &&
    formInfo.value.data.details &&
    formInfo.value.data.details.length
  ) {
    let sumAmount = 0
    formInfo.value.data.details.forEach((item) => {
      item.price = val
      item.sumAmount = proxy.$fn.accDiv(
        proxy.$fn.accMul(item.price || 0, item.calcQty || 0),
        item.unitConvertCoefficient || 1
      )
      sumAmount = proxy.$fn.accAdd(sumAmount, item.sumAmount || 0)
    })
    formInfo.value.data.sumAmount = sumAmount
  }
}
function changeSterilization(val) {
  if (
    formInfo.value.data.codeType === 3 &&
    formInfo.value.data.details &&
    formInfo.value.data.details.length
  ) {
    formInfo.value.data.details.forEach((item) => {
      item.sterilizationNumber = val
    })
  }
}
function handleClose() {
  dialogInfo.value.visible = false
  formInfo.value.data = {}
}
function checkConfirm() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      if (formInfo.value.data.codeType === 3) {
        if (!formInfo.value.data.details.length) {
          proxy.$message({
            message: `重新发货列表不能为空`,
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
          return
        }
        let nameList = formInfo.value.data.details
          .filter((item) => item.calcQty <= 0)
          .map((item) => item.factorySubCode)
        if (nameList.length) {
          proxy.$message({
            message: '重新发货列表【' + nameList + '】发货数量必须大于0',
            type: 'warning',
            duration: 3500,
            showClose: true,
          })
          return
        }
      }
      let mergeDetails = proxy.$fn.deepClone(tableInfo.value.data)
      mergeDetails[formInfo.value.index] = formInfo.value.data
      const params = {
        ...infoList.value.data,
        mergeDetails: mergeDetails,
      }
      deliverOrderReshipment(params).then((res) => {
        if (res && res.success) {
          returnDetail()
          handleClose()
        }
      })
    }
  })
}
function afreshInvoce(row, index) {
  //重新发货
  dialogInfo.value.visible = true
  formInfo.value.index = index
  formInfo.value.data = proxy.$fn.deepClone(row)
  formInfo.value.data.largeUnitQty = 0
  formInfo.value.data.smallUnitQty = 0
  formInfo.value.data.calcQty = 0
  formInfo.value.data.qty = 0
  scanInfo.value.getProductIds = [row.productId]
  if (row.codeType == 3) {
    formInfo.value.data.details = []
  }
}
function revokeInvoce(row) {
  //撤销发货
  let mergeDetails = proxy.$fn.deepClone(tableInfo.value.data)
  mergeDetails = mergeDetails.filter((item) => item.uuid !== row.uuid)
  const params = {
    ...infoList.value.data,
    mergeDetails: mergeDetails,
  }
  deliverOrderReshipment(params).then((res) => {
    if (res && res.success) {
      returnDetail()
      handleClose()
    }
  })
}
function remove(row) {
  formInfo.value.data.details = formInfo.value.data.details.filter(
    (item) => item != row
  )
  if (formInfo.value.data.details && formInfo.value.data.details.length) {
    let largeUnitQty = 0
    let smallUnitQty = 0
    let calcQty = 0
    formInfo.value.data.details.forEach((item) => {
      largeUnitQty = proxy.$fn.accAdd(item.largeUnitQty, largeUnitQty)
      smallUnitQty = proxy.$fn.accAdd(item.smallUnitQty, smallUnitQty)
      calcQty = proxy.$fn.accAdd(item.calcQty, calcQty)
    })
    formInfo.value.data.largeUnitQty = largeUnitQty
    formInfo.value.data.smallUnitQty = smallUnitQty
    formInfo.value.data.calcQty = calcQty
    formInfo.value.data.qty = proxy.$fn.accDiv(
      calcQty,
      formInfo.value.data.unitConvertCoefficient
    )
  } else {
    formInfo.value.data.largeUnitQty = 0
    formInfo.value.data.smallUnitQty = 0
    formInfo.value.data.calcQty = 0
    formInfo.value.data.qty = 0
    formInfo.value.data.flag = false
  }
}
function onCallBackScanData(obj) {
  let data = formInfo.value.data
  console.log(obj.data)
  if (data.calcQty >= data.deliverableCalcQty) {
    proxy.$message({
      message: `扫除产品已处理完`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  obj.data.isConsignBusiness = infoList.value.data.isConsignBusiness
  let details = formInfo.value.data.details
  if (details && details.length) {
    details.forEach((row) => {
      row.isChioce = false
    })
  }
  if (obj.flag === 1) {
    let data = obj.data
    data.price = formInfo.value.data.price
    data.sterilizationNumber = formInfo.value.data.sterilizationNumber || ''
    data.flag = true
    data.sumAmount = proxy.$fn.accDiv(
      proxy.$fn.accMul(data.price || 0, data.calcQty || 0),
      data.unitConvertCoefficient || 1
    )
    data.details = [proxy.$fn.deepClone(data)]
    data.factoryMainCode = ''
    data.factorySubCode = ''
    data.gs1Code = ''
    formInfo.value.data = data
    proxy.$message({
      message: `扫码成功`,
      type: 'success',
      duration: 3500,
      showClose: true,
    })
  } else if (obj.flag === 2) {
    let item = proxy.$fn.deepClone(formInfo.value.data)
    let data = obj.data
    data.price = formInfo.value.data.price
    data.sterilizationNumber = formInfo.value.data.sterilizationNumber || ''
    data.isChioce = true
    item.details.unshift(data)
    item.calcQty = proxy.$fn.accAdd(item.calcQty, data.calcQty || 0)
    item.qty = proxy.$fn.accAdd(item.qty, data.qty || 0)
    item.flag = true
    item.largeUnitQty = proxy.$fn.accAdd(
      item.largeUnitQty,
      data.largeUnitQty || 0
    )
    item.smallUnitQty = proxy.$fn.accAdd(
      item.smallUnitQty,
      data.smallUnitQty || 0
    )
    item.sumAmount = proxy.$fn.accAdd(
      item.sumAmount,
      proxy.$fn.accDiv(
        proxy.$fn.accMul(data.price || 0, data.calcQty || 0),
        data.unitConvertCoefficient || 1
      )
    )
    formInfo.value.data = item
    proxy.$message({
      message: `扫码成功`,
      type: 'success',
      duration: 3500,
      showClose: true,
    })
  } else if (obj.flag === 3) {
    proxy.$message({
      message: `扫码产品不在当前重新发货范围内`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChioce) {
    return 'success-row'
  } else {
    return ''
  }
}
function returnReceiving(str) {
  if (!str) {
    showDialog.value = false
    emit('returnBack', false)
  }
}
onMounted(() => {
  if (props.id) {
    getMain()
    getList()
  }
})
</script>
<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
:deep(.el-dialog__body) {
  height: 355px;
  display: flex;
  flex-direction: column;
}
</style>
